﻿using GoodDotNet.Core.Model;
using GoodDotNet.Service;
using GoodDotNet.App.Filter;
using log4net;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.OpenApi.Models;
using System;
using System.IO;
using System.Linq;
using System.Reflection;


namespace GoodDotNet.App.Extensions
{
    /// <summary>
    /// Swagger 启动服务
    /// </summary>
    public static class SwaggerSetup
    {

        private static readonly ILog log =
        LogManager.GetLogger(typeof(GlobalExceptionsFilter));

        public static void AddSwaggerSetup(this IServiceCollection services,SwaggerSetting swagger)
        {
            if (services == null) throw new ArgumentNullException(nameof(services));

            var basePath = AppContext.BaseDirectory;
            //var basePath2 = Microsoft.DotNet.PlatformAbstractions.ApplicationEnvironment.ApplicationBasePath;
             services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc(swagger.Version, new OpenApiInfo
                {
                    Title = swagger.ApiName,
                    Version = swagger.Version,
                    Description =swagger.Description
                });
               

                try
                {
                    string basePath = AppDomain.CurrentDomain.BaseDirectory;
                 
                    var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                    c.IncludeXmlComments(Path.Combine(basePath, xmlFile), true); // true : 显示控制器层注释
                    foreach (var model in swagger.Model)
                    {
                        c.IncludeXmlComments(Path.Combine(basePath, model+ ".xml"));
                    }

                    c.OrderActionsBy(o => o.RelativePath); // 对action的名称进行排序，如果有多个，就可以看见效果了。
                }
                catch (Exception ex)
                {
                    log.Error("GoodDotNet.xml和GoodDotNet.Core.Model.xml 丢失，请检查并拷贝。\n" + ex.Message);
                }

                //c.OperationFilter<AddResponseHeadersFilter>();
                //c.OperationFilter<AppendAuthorizeToSummaryOperationFilter>();

                //c.OperationFilter<SecurityRequirementsOperationFilter>();


                // Token绑定到ConfigureServices
                c.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
                {
                    Description = "JWT授权(数据将在请求头中进行传输) 直接在下框中输入Bearer {token}（注意两者之间是一个空格）\"",
                    Name = swagger.Token,//jwt默认的参数名称
                    In = ParameterLocation.Header,//jwt默认存放Authorization信息的位置(请求头中)
                    Type = SecuritySchemeType.ApiKey
                });
            });

        }
       
    }
}
